import { useEffect } from "react";
import { Space, Divider, Table, message, Popconfirm } from "antd";
import { Button, ButtonGroup, Card as SemiCard } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { useModel, history } from "umi";
import { useReactive } from "ahooks";
import { useRelatedOrganization } from "@share-code/public";

const { Column } = Table;

const AllApplyAndApproveAffiliateOrganizations = () => {
    const { remoteData, UTCTimeToLocal, windowInnerHeight, graphqlFetch } = useModel("global");
    const { baseInfo } = useModel("person.info");
    const { organizationUuid, organizationInfo } = useModel("organization.info");

    const { loadAllRelatedOrganizationsApplyingAndApprove, updateRelatedOrganizationStatus } =
        useRelatedOrganization(graphqlFetch);

    const state = useReactive({
        loading: false,
        applyings: [],
        verifies: [],
    });

    const loadAffiliates = async () => {
        state.loading = true;
        let res = await loadAllRelatedOrganizationsApplyingAndApprove();
        state.applyings = res?.applies || [];
        state.verifies = res?.approves || [];
        state.loading = false;
        if (state.verifies.length === 0 && state.applyings.length === 0) history.replace("/all");
    };

    useEffect(() => {
        loadAffiliates();
    }, []);

    const reApply = async (item) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: item.oaUuid,
            params: {
                apiPath: "/organization/relatedApply",
                data: {
                    oaUuid: organizationUuid,
                    oaName: organizationInfo.fullName,
                    oaCaus: "重新申请",
                    oaApid: baseInfo.uuid,
                    oaApna: baseInfo.realName,
                },
            },
        });
        if (res) {
            if (res?.oaStat === "待审核") {
                message.warning((res?.oaCaus ? res.oaCaus + ", " : "") + "申请待审核中");
            }
            if (res?.oaStat === "正常") {
                res = await updateRelatedOrganizationStatus({
                    oaUuid: item.oaUuid,
                    oaStat: "正常",
                    oaAust: true,
                });
                message.success("申请关联的组织已确认");
                loadAffiliates();
            }
        }
    };

    // 核准
    const handlePass = async (record, index) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedReply",
                data: {
                    oaUuid: organizationUuid,
                    oaStat: "正常",
                },
            },
        });
        if (res) {
            res = await updateRelatedOrganizationStatus({
                oaUuid: record.oaUuid,
                oaStat: "正常",
                oaAust: true,
            });
            if (res) {
                message.success("批准组织关联操作成功");
                await loadAffiliates();
            }
        }
    };

    // 已驳回
    const handleRefuse = async (record, index) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedReply",
                data: {
                    oaUuid: organizationUuid,
                    oaStat: "已驳回",
                },
            },
        });
        if (res) {
            res = await updateRelatedOrganizationStatus({
                oaUuid: record.oaUuid,
                oaStat: "已驳回",
                oaAust: false,
            });
            if (res) {
                message.success("驳回组织关联操作成功");
                loadAffiliates();
            }
        }
    };

    // 已拒绝
    const handleReject = async (record, index) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedReply",
                data: {
                    oaUuid: organizationUuid,
                    oaStat: "已拒绝",
                },
            },
        });
        if (res) {
            res = await updateRelatedOrganizationStatus({
                oaUuid: record.oaUuid,
                oaStat: "已拒绝",
                oaAust: false,
            });
            if (res) {
                message.success("拒绝组织关联操作成功");
                loadAffiliates();
            }
        }
    };

    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：53，卡面脚：56，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 20;
    const tableBodyHeight = (cardBodyHeight - 10 - 48 - 48) / 2;

    return (
        <div>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 15 }}>申请中组织列表</span>}
                headerStyle={{ padding: "7px 12px" }}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconRefresh />} onClick={() => loadAffiliates()}>
                            刷新
                        </Button>
                    </ButtonGroup>
                }
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: tableBodyHeight }}
            >
                <Table
                    loading={state.loading}
                    bordered
                    size="small"
                    pagination={false}
                    dataSource={state.verifies}
                    rowKey={"oaUuid"}
                    scroll={{ y: tableBodyHeight - 40 }}
                >
                    <Column
                        title="序号"
                        dataIndex="orderNo"
                        align="center"
                        width={80}
                        render={(_, record, index) => ++index}
                    />
                    <Column title="组织名称" dataIndex="oaName" align="left" />
                    <Column title="组织关系" dataIndex="oaRela" align="center" />
                    <Column title="关联原由" dataIndex="oaCaus" align="center" />
                    <Column
                        title="申请时间"
                        align="center"
                        width={160}
                        render={(_, record) => UTCTimeToLocal(record.oaApti)}
                    />
                    <Column
                        title="是否发起方"
                        align="center"
                        width={120}
                        render={(_, record) => (record.oaIsme ? "是" : "否")}
                    />
                    <Column
                        title="审核状态"
                        align="center"
                        width={100}
                        render={(_, record) =>
                            record.oaAust ? <span className="green">已核准</span> : <span className="red">待核准</span>
                        }
                    />
                    <Column title="关系状态" dataIndex="oaStat" align="center" width={100} />
                    <Column
                        title="操作"
                        key="operations"
                        align="center"
                        width={160}
                        render={(_, record) => {
                            if (record.oaStat === "已驳回") {
                                return (
                                    <Space split={<Divider type="vertical" />} size={0}>
                                        <a onClick={() => reApply(record)}>重新申请</a>
                                    </Space>
                                );
                            }
                        }}
                    />
                </Table>
            </SemiCard>

            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 15 }}>待审核组织列表</span>}
                headerStyle={{ padding: "7px 12px" }}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconRefresh />} onClick={() => loadAffiliates()}>
                            刷新
                        </Button>
                    </ButtonGroup>
                }
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: tableBodyHeight }}
                style={{ marginTop: 10 }}
            >
                <Table
                    loading={state.loading}
                    bordered
                    size="small"
                    pagination={false}
                    dataSource={state.applyings}
                    rowKey={"oaUuid"}
                    scroll={{ y: tableBodyHeight - 40 }}
                >
                    <Column
                        title="序号"
                        dataIndex="orderNo"
                        align="center"
                        width={80}
                        render={(_, record, index) => ++index}
                    />
                    <Column title="组织名称" dataIndex="oaName" align="left" />
                    <Column title="组织关系" dataIndex="oaRela" align="center" />
                    <Column title="关联原由" dataIndex="oaCaus" align="center" />
                    <Column
                        title="申请时间"
                        align="center"
                        width={160}
                        render={(_, record) => UTCTimeToLocal(record.oaApti)}
                    />
                    <Column
                        title="是否发起方"
                        align="center"
                        width={120}
                        render={(_, record) => (record.oaIsme ? "是" : "否")}
                    />
                    <Column
                        title="审核状态"
                        align="center"
                        width={100}
                        render={(_, record) =>
                            record.oaAust ? <span className="green">已核准</span> : <span className="red">待核准</span>
                        }
                    />
                    <Column title="关系状态" dataIndex="oaStat" align="center" width={100} />
                    <Column
                        title="操作"
                        key="operations"
                        align="center"
                        width={160}
                        render={(_, record, index) => {
                            return (
                                <Space split={<Divider type="vertical" />} size={0}>
                                    <Popconfirm
                                        title="确认要批准该组织的关联申请吗?"
                                        onConfirm={() => handlePass(record, index)}
                                    >
                                        <a>核准</a>
                                    </Popconfirm>
                                    <Popconfirm
                                        title="确认要驳回该组织的关联申请吗?"
                                        placement="topRight"
                                        onConfirm={() => handleRefuse(record, index)}
                                    >
                                        <a>驳回</a>
                                    </Popconfirm>
                                    <Popconfirm
                                        title="确认要拒绝该组织的关联申请吗?"
                                        placement="topRight"
                                        onConfirm={() => handleReject(record, index)}
                                    >
                                        <a>拒绝</a>
                                    </Popconfirm>
                                </Space>
                            );
                        }}
                    />
                </Table>
            </SemiCard>
        </div>
    );
};

export default AllApplyAndApproveAffiliateOrganizations;
